package com.xh.xyzp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xh.xyzp.common.constant.UserContext;
import com.xh.xyzp.common.domain.vo.resp.PageResp;
import com.xh.xyzp.common.enums.CommonStatusTypeEnum;
import com.xh.xyzp.domain.entity.Resume;
import com.xh.xyzp.domain.vo.ResumePageReq;
import com.xh.xyzp.domain.vo.ResumeSubmitReq;
import com.xh.xyzp.exception.ApiException;
import com.xh.xyzp.mapper.ResumeMapper;
import com.xh.xyzp.service.ResumeService;
import com.xh.xyzp.util.SnowFlakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements ResumeService {

    @Autowired
    private ResumeMapper resumeMapper;

    @Override
    public void submit(ResumeSubmitReq req) {
        req.checkParams();
        Resume resume = getInfoByUserId(UserContext.getUser().getId());
        if (Objects.isNull(resume)) {
            resume = BeanUtil.copyProperties(req, Resume.class);
            resume.setId(new SnowFlakeIdWorker(1, 0).nextId());
            resume.setUserId(UserContext.getUser().getId());
            save(resume);
        } else {
            BeanUtils.copyProperties(req, resume);
            updateById(resume);
        }
    }

    @Override
    public PageResp<Resume> getList(ResumePageReq req) {
        req.checkParams();
        LambdaQueryWrapper<Resume> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<Resume> resumePage = resumeMapper.selectPage(new Page<>(req.getCurrPage(), req.getPageSize()), lambdaQueryWrapper);
        return PageResp.<Resume>builder()
                .list(resumePage.getRecords())
                .total(resumePage.getTotal())
                .build();
    }

    @Override
    public Resume getInfo(Long resumeId) {
        if (Objects.isNull(resumeId)) {
            throw new ApiException("id不能为空");
        }
        return lambdaQuery()
                .eq(Resume::getId, resumeId)
                .eq(Resume::getStatus, CommonStatusTypeEnum.NORMAL.getKey())
                .one();
    }

    @Override
    public Resume getInfoByUserId(Long userId) {
        Resume one = lambdaQuery().eq(Resume::getUserId, userId).one();
        if (Objects.isNull(one)) {
            return null;
        }
        return one;
    }


}